//
//  SHLocationServicesManager.m
//  SHLocationServices
//
//  Created by suoxiaoxiao on 2019/6/26.
//

#import "SHLocationServicesManager.h"


@interface SHLocationServicesManager ()
<CLLocationManagerDelegate>

@property (strong,nonatomic) CLLocationManager* locationManager;
@property (nonatomic , copy) LocalCoordinateResultSuccessBlock succlocalBlock;
@property (nonatomic , copy) LocalResultErrorBlock errorBlock;

@end

@implementation SHLocationServicesManager

+ (instancetype)shared {
    
    static SHLocationServicesManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [SHLocationServicesManager new];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.locationManager = [[CLLocationManager alloc] init];
        
        self.locationManager.delegate = self;
        
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        self.locationManager.distanceFilter = 100.0f;
        
        
    }
    return self;
}

+ (void)startCoordinateLocalSuccess:(LocalCoordinateResultSuccessBlock)resultBlock fail:(LocalResultErrorBlock)errorBlock {
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    switch (status) {
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
            if (errorBlock) {
                NSError *error = [NSError errorWithDomain:@"权限受限" code:SHLocationServicesErrorCodeAuthorizationDenied userInfo:nil];
                errorBlock(error);
            }
            return ;
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusNotDetermined:
            break;
    }
    
    if ([[[UIDevice currentDevice] systemVersion]doubleValue] >8.0){
        
        [[SHLocationServicesManager shared].locationManager requestWhenInUseAuthorization];
        
    }
    
    if (resultBlock) {
        [SHLocationServicesManager shared].succlocalBlock = resultBlock;
    }
    if (errorBlock) {
        [SHLocationServicesManager shared].errorBlock = errorBlock;
    }

    [[SHLocationServicesManager shared].locationManager startUpdatingLocation];
}


+ (void)stopLocal {
    
    [[SHLocationServicesManager shared].locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    switch (status) {
            
        case kCLAuthorizationStatusNotDetermined:
            
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
                
                [self.locationManager requestWhenInUseAuthorization];
                
            }break;
            
        default:break;
    }
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *newLocation = locations[0];
    
    [manager stopUpdatingLocation];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks && placemarks.count > 0) {
            
            CLPlacemark *place = placemarks[0];
            
            NSLog(@"thoroughfare,%@",place.thoroughfare);// 街道
            
            NSString *province = place.administrativeArea;
            
            NSLog(@"administrativeArea %@",place.administrativeArea);//省
            //NSLog(@"subThoroughfare,%@",place.subThoroughfare);// 子街道
            
            NSLog(@"locality,%@",place.locality);// 市
            
           // 详细地址
            NSString *address = [NSString stringWithFormat:@"%@%@%@%@%@",province ?:@"",place.locality?:@"", place.subLocality?:@"",place.thoroughfare?:@"",place.subThoroughfare?:@""];
            
            if (!province) {
                //4个直辖市
                if ([place.locality isEqualToString:@"上海市"] ||
                    [place.locality isEqualToString:@"北京市"] ||
                    [place.locality isEqualToString:@"天津市"] ||
                    [place.locality isEqualToString:@"重庆市"]) {
                    province = place.locality;
                }
                //5个自治区
            }
            
            NSLog(@"subLocality,%@",place.subLocality);// 区
            
            NSLog(@"country,%@",place.country);// 国家
            
            if ([SHLocationServicesManager shared].succlocalBlock) {
                [SHLocationServicesManager shared].succlocalBlock(place.country ?: @"" ,province ?: @"",place.locality ?: @"",place.subLocality ?: @"",place.thoroughfare ?: @"",address,newLocation);
            }
            
        }else{
            
            if ([SHLocationServicesManager shared].errorBlock) {
                NSError *error = [NSError errorWithDomain:@"反地理编码错误" code:SHLocationServicesErrorCodeGeocoderError userInfo:nil];
                [SHLocationServicesManager shared].errorBlock(error);
                [SHLocationServicesManager shared].errorBlock = nil;
            }
            
        }
    }];
}

@end
